<?php

namespace app\user\controller\training\list;

use app\admin\service\ReportService;
use app\admin\service\UserService;
use app\BaseController;
use app\model\training\TrainingTaskDepartmentModel;
use app\model\training\TrainingTaskModel;
use app\model\training\TrainingTaskUserModel;
use app\model\training\TrainingTaskUserResultModel;
use app\user\service\TrainingService;
use think\App;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 培训讲座列表
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'pageSize|每页显示数量' => 'require',
            ]);
            $where = [];
            if (!empty($param['name'])){
                $where[] = ['name','like','%'.$param['name'].'%'];
            }
            if (!empty($param['type_id'])){
                $where[] = ['type_id','=',$param['type_id']];
            }
            if (!empty($param['uid'])){
                $where[] = ['uid','=',$param['uid']];
            }
            $where[] = ['status','=',1];
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $TrainingTaskModel = new TrainingTaskModel();
            $data = $TrainingTaskModel->where($where)->with([
                'TrainingLecturer',
                'typeName',
                'textbook' => function($query){
                    $query->with(['textbookType']);
                }
            ])->paginate($param['pageSize'])->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 详情
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|integer',
            ]);
            $TrainingTaskModel = new TrainingTaskModel();
            $info = $TrainingTaskModel->with([
                'user',
                'TrainingLecturer',
                'typeName',
                'textbook',
                'TrainingTaskDepartment',
                'TrainingTaskRatingScaleFront' => function($query){
                    $query->with(['ratingScale']);
                },
                'TrainingTaskRatingScaleAfter' => function($query){
                    $query->with(['ratingScale']);
                }
            ])->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            $TrainingTaskUserResultModel = new TrainingTaskUserResultModel();
            if (!empty($info['TrainingTaskRatingScaleFront'])){
                foreach ($info['TrainingTaskRatingScaleFront'] as &$value){
                    $result = $TrainingTaskUserResultModel->field('id,callable_view')->where([
                        ['task_id','=',$param['id']],
                        ['uid','=',$this->userData['id']],
                        ['type','=',1],
                        ['rating_scale_id','=',$value['rating_scale_id']]
                    ])->find();
                    if ($result){
                        $value['result_id'] = $result['id'];
                        $value['callable_view'] = $result['callable_view'];
                    }else{
                        $value['result_id'] = 0;
                        $value['callable_view'] = 0;
                    }
                }
            }
            if (!empty($info['TrainingTaskRatingScaleAfter'])){
                foreach ($info['TrainingTaskRatingScaleAfter'] as &$value){
                    $result = $TrainingTaskUserResultModel->field('id,callable_view')->where([
                        ['task_id','=',$param['id']],
                        ['uid','=',$this->userData['id']],
                        ['type','=',2],
                        ['rating_scale_id','=',$value['rating_scale_id']]
                    ])->find();
                    if ($result){
                        $value['result_id'] = $result['id'];
                        $value['callable_view'] = $result['callable_view'];
                    }else{
                        $value['result_id'] = 0;
                        $value['callable_view'] = 0;
                    }
                }
            }
            if (!empty($info['TrainingTaskDepartment'])){
                $UserService = new UserService($this->app);
                $allDepartment = $UserService->getNotDelDepartmentAffiliationAll($this->userData['unit_id']);
                foreach ($info['TrainingTaskDepartment'] as &$department){
                    $department['name'] = $allDepartment[$department['department_id']]['all_name']??'--';
                }
            }
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 测评结果
     * @return bool|string
     */
    public function resultInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|integer',
            ]);
            $ReportService = new ReportService($this->app);
            $data = $ReportService->getTrainingReportInfo($param['id']);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 测评结果
     * @return bool|string
     */
    public function resultInfo2(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|integer',
            ]);
            $ReportService = new ReportService($this->app);
            $data = $ReportService->getTrainingEvaluationReportInfo($param['id']);
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 提交测评
     * @return bool|string
     */
    public function submitTaskEvaluationResults(): bool|string
    {
        $TrainingTaskModel = new TrainingTaskModel();
        $TrainingTaskModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'task_id|任务ID' =>  'require',
//                'task_user_id|用户任务表ID' =>  'require',
                'rating_scale_id|量表ID' =>  'require',
                'finish_used_time|用户完成用时' =>  'require',
                'type|任务类型' => 'require'
            ]);
            //不可重复提交
            $TrainingTaskUserResultModel = new TrainingTaskUserResultModel();
            $TrainingTaskUserModel = new TrainingTaskUserModel();
            $ResultInfo = $TrainingTaskUserResultModel->where([
                ['task_id','=',$param['task_id']],
                ['task_user_id','=',$param['task_user_id']??0],
                ['rating_scale_id','=',$param['rating_scale_id']],
                ['uid','=',$this->userData['id']],
                ['type','=',$param['type']],
            ])->find();
            if ($ResultInfo) throw new \Exception('不可重复提交！');
            $taskInfo = $TrainingTaskModel->find($param['task_id']);
            if (!$taskInfo) throw new \Exception('参数错误！');
            if ($param['type'] == 2 && $taskInfo['status'] < 3) throw new \Exception('课后测评任务需要课程结束后才可测评！');
            if (!empty($param['task_user_id'])){
                $taskUserInfo = $TrainingTaskUserModel->find($param['task_user_id']);
                if (!$taskInfo || !$taskUserInfo) throw new \Exception('参数错误！');
                switch ($param['type']){
                    case 1:
                        //前置
                        if ($taskUserInfo['is_finish_front'] == 1) break;
                        $front_num = $TrainingTaskUserResultModel->where([
                            ['task_user_id','=',$param['task_user_id']],
                            ['type','=',1]
                        ])->count();
                        if ($front_num+1 == $taskInfo['front_num']){
                            $taskUserInfo->save([
                                'is_finish_front' => 1
                            ]);
                        }
                        break;
                        case 2:
                            //课后
                            if ($taskUserInfo['is_finish_after'] == 1) break;
                            $after_num = $TrainingTaskUserResultModel->where([
                                ['task_user_id','=',$param['task_user_id']],
                                ['type','=',2]
                            ])->count();
                            if ($after_num+1 == $taskInfo['after_num']){
                                $taskUserInfo->save([
                                    'is_finish_after' => 1
                                ]);
                            }
                            break;
                }
            }
            $TrainingService = new TrainingService($this->app);
            if (!$TrainingService->generateReport([
                'company_id' => $this->userData['company_id'],//公司
                'areas_id' => $this->userData['areas_id'],//区域
                'unit_id' => $this->userData['unit_id'],
                'uid' => $this->userData['id'],//答题用户ID
                'task_id' => $param['task_id'],//任务ID
                'task_user_id' => $param['task_user_id']??0,//用户任务表ID
                'rating_scale_id' => $param['rating_scale_id'],//量表ID
                'type' => $param['type'],//测评类型
                'userAnswer' => $param['question_answer']??[],//用户填写的答案
                'finish_used_time' => $param['finish_used_time'],//用户完成用时
            ],9))
                throw new \Exception($TrainingService->message);
            $TrainingTaskModel->commit();
            return success([
                'result_id' => $TrainingService->ResultId,
                'data' => $TrainingService->resultData,
                'is_valid' => $TrainingService->is_valid
            ],'提交成功！');
        } catch (\Exception $e) {
            $TrainingTaskModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 报名
     * @return bool|string
     */
    public function signUp(): bool|string
    {
        $TrainingTaskModel = new TrainingTaskModel();
        $TrainingTaskModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
            ]);
            $info = $TrainingTaskModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $TrainingTaskUserModel = new TrainingTaskUserModel();
            $log = $TrainingTaskUserModel->where([
                ['task_id','=',$param['id']],
                ['audit_status','in',[1,2]],
                ['uid','=',$this->userData['id']],
            ])->value('id');
            if ($log) throw new \Exception('不可重复报名！');
            $addData = [
                'unit_id' => $this->userData['unit_id'],
                'task_id' => $param['id'],
                'uid' => $this->userData['id'],
                'time' => time()
            ];
            if ($info['review'] == 0){
                $addData['audit_status'] = 2;
                $info->inc('review_num')->save();
                $TrainingTaskDepartmentModel = new TrainingTaskDepartmentModel();
                $TrainingTaskDepartmentModel->where([
                    ['task_id','=',$param['id']],
                    ['department_id','=',$this->userData['department_id']]
                ])->inc('user_num')->save();
            }
            $TrainingTaskUserResultModel = new TrainingTaskUserResultModel();
            if (!empty($param['result_id'])){
                if ($info['front_num'] > 0){
                    $front_num = $TrainingTaskUserResultModel->where([
                        ['id','in',$param['result_id']],
                        ['type','=',1]
                    ])->count();
                    if ($front_num == $info['front_num']){
                        $addData['is_finish_front'] = 1;
                    }
                }
               if ($info['after_num'] > 0){
                   $after_num = $TrainingTaskUserResultModel->where([
                       ['id','in',$param['result_id']],
                       ['type','=',2]
                   ])->count();
                   if ($after_num == $info['after_num']){
                       $addData['is_finish_after'] = 1;
                   }
               }
            }
            $task_user_id = $TrainingTaskUserModel->insertGetId($addData);
            //绑定测评结果
            if (!empty($param['result_id'])){
                $TrainingTaskUserResultModel->where('id','in',$param['result_id'])->update([
                    'task_user_id' => $task_user_id
                ]);
            }
            $TrainingTaskModel->commit();
            return success($info);
        } catch (\Exception $e) {
            $TrainingTaskModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }
}